package servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import actionForm.CreateContactGroupValidationForm;
import domain.ContactGroup;
import domain.IDAOContactGroup;

public class ModifyContactGroupAction extends Action {
	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest request,
			final HttpServletResponse response) {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		IDAOContactGroup dao = (IDAOContactGroup) context.getBean("daocontactgroup");
		if (request.getMethod().equals("POST")) {
			CreateContactGroupValidationForm form = (CreateContactGroupValidationForm) pForm;
			final String id = request.getParameter("id");
			final String groupName = form.getGroupName();
			boolean success = dao.modifyContactGroup(Long.valueOf(id), groupName);
			if (success) {
				request.setAttribute("successMessage", "The contact group has been updated." );
				return pMapping.findForward("success");
			}
			else {
				request.setAttribute("errorMessage", "The contact group could not be updated.");
				return pMapping.findForward("error");			
			}
		}
		else if (request.getMethod().equals("GET")){
			String id = request.getParameter("id");
			request.setAttribute("groups", dao.getContactGroups().toArray());
			ContactGroup contactGroup = dao.getContactGroup(Long.valueOf(id));
			if ( contactGroup != null ) {
				request.setAttribute("group", contactGroup );
				return pMapping.findForward("modifyContactGroup");
			}
			else {
				request.setAttribute("errorMessage", "The contact doesn't exist.");
				return pMapping.findForward("error");			
			}
		}
		return null;
	}
}